package com.gopay.cashier.service.impl;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.web.controller.BaseController;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.pg.PgBtOrderTransDtl;
import com.gopay.common.domain.pg.PgGenOrderTransDtl;
import com.gopay.common.domain.pg.PgP2pOrderTransDtl;
import com.gopay.common.util.NumberUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * Created by HJY on 2015/5/28.
 */
@Service("antiPhishService")
public class AntiPhishServiceImpl extends BaseController {

    public String[] getAntiPhishInfo(CpsGenMainOrder order) throws WebException {
        String randomStr = "8888"; // update by dongdh 给成固定值 RandomStringUtils.randomAlphabetic(4).toLowerCase();
        String merRefer = "";
        String merName = "--";
        String tranAmt = "0.00";
        String goodsInfo = "--";

        tranAmt = NumberUtils.format2PointWithHalfUp(order.getMerTxnAmt());

        // 如果该订单是充值订单，则需要通过关联订单号获取对应的支付/入金订单
        if (IntTxnCd._00500.value.equals(order.getGopayIntTxnCd())
                && StringUtils.isNotEmpty(order.getRelevanceGopayOrderId())) {
            order = getMainOrder(order.getRelevanceGopayOrderId(), true);
        }

        CustCorpInfo cci = custCorpInfoService.get(order.getMainRecvCustId());
        if (cci != null && StringUtils.isNotBlank(cci.getMerName())) {
            merName = cci.getMerName();
        }

        // 如果是大宗入金交易，从大宗流水表中获取信息。目前收银台被业务入侵严重，后期应考虑重构
        if (IntTxnCd._00200.value.equals(order.getGopayIntTxnCd())) {
            PgBtOrderTransDtl pgOrder = pgBTOrderTransDtlQueryManager.get(order.getTransDtlSq());
            if (pgOrder != null) {
                merRefer = pgOrder.getMerRefer();
            }
        } if(isP2P(order)){
            PgP2pOrderTransDtl pgOrder =  pgP2pOrderTransDtlQueryManager.get(order.getTransDtlSq());
            merRefer = pgOrder.getReqRefer();
        }else {
            PgGenOrderTransDtl pgOrder = pgGeneralOrderTransDtlQueryManager.get(order.getTransDtlSq());
            merRefer = pgOrder.getMerRefer();
            goodsInfo = StringUtils.isNotEmpty(pgOrder.getGoodsInfo()) ? pgOrder.getGoodsInfo() : pgOrder
                    .getGoodsName();
        }

        if (StringUtils.isBlank(merRefer)) {
            merRefer = "";
        }

        return new String[] { randomStr, merName, tranAmt, merRefer, goodsInfo };
    }
}
